﻿var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var compress = require('compression');
var fs = require('fs');
var Wechat = require('./wechat.js');
var cookieParser = require("cookie-parser");
var admin = require('./routes/admin.js');
var Oracledb = require("./db/Oracledb.js");
var Msdb = require("./db/Msdb.js");
const jwt = require('jsonwebtoken');
const expressJwt = require('express-jwt');
const nodeExcel = require('excel-export');
var Excel = require('exceljs');
const log = require('./logger');
var logger = require('./logger').logger;
const crypto = require('crypto');
var Mysqldb = require('./db/Mysqldb.js');
var Mysqldb_copy = require('./db/Mysqldb copy.js');
var UUID = require('uuid');
var Redisdb = require('./db/Redisdb.js');
var request = require("request");
const e = require('express');
const schedule = require('node-schedule');
const WebSocket = require('ws');
const http = require('http');
const { usequery, res_util, getnowdate } = require('./routes/adminroute/shipSRM/server_util.js');
const { xm_fb, xm_ybjz, xm_tbjz, xm_kb, update_gysjb, update_gysjb_pm, xm_xbjz, update_gysbqxj, xm_tbkz, xm_pbjz, xm_lxjz } = require('./routes/adminroute/shipSRM/chmes_sys_ddd_util.js');
const DingTalk = require('./dingtalk.js');
const secret = 'cxcx';

log.use(app);
//手动记录，可以代替console.log
logger.info('test info 1');



app.use(compress());
app.use(express.static("../opt"));

app.use(express.static("dist"));
app.use(express.static("dist2"));
app.use(express.static("uploads"));
app.use(express.static("public"));
app.use(bodyParser.json({ limit: '50mb' })); // for parsing application/json
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
app.use(cookieParser());


//拦截器
app.use(function (err, req, res, next) {
  //当token验证失败时会抛出如下错误

  if (err.name === 'UnauthorizedError') {
    //这个需要根据自己的业务逻辑来处理（ 具体的err值 请看下面）
    console.log("无效权限")
    console.log("err  " + JSON.stringify(err))
    res.status(401).send('invalid token...');
  }
});

//路由模块化
app.use('/admin', admin);


// 获取钉钉登录二维码
app.post('/admin/sys/getDingTalkLoginUrl', async function(req, res) {
  const dingtalk = new DingTalk();
  const result = await dingtalk.getLoginQrCode();
  res.json(result);
});

// 检查钉钉登录状态
app.post('/admin/sys/checkDingTalkLogin', async function(req, res) {
  const { code } = req.body;
  const dingtalk = new DingTalk();
  const result = await dingtalk.checkLoginStatus(code);
  res.json(result);
});

// 钉钉登录回调
app.get('/admin/sys/dingtalk/callback', async function(req, res) {
  const { code, state } = req.query;
  logger.info('钉钉登录回调参数:', { code, state });

  if (!code) {
    logger.error('钉钉登录回调缺少code参数');
    res.redirect('/#/login?error=missing_code');
    return;
  }

  try {
    const dingtalk = new DingTalk();
    const result = await dingtalk.checkLoginStatus(code);
    
    if (result.success) {
      // 登录成功，重定向到前端页面并带上授权码
      res.redirect(`/#/login?code=${code}`);
    } else {
      // 登录失败，重定向到错误页面
      logger.error('钉钉登录失败:', result.message);
      res.redirect(`/#/login?error=${encodeURIComponent(result.message)}`);
    }
  } catch (error) {
    logger.error('处理钉钉登录回调失败:', error);
    res.redirect('/#/login?error=server_error');
  }
});



const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
var clients = {};

wss.on('connection', (ws) => {
  var wsid = UUID.v1();
  var wsid_timer = wsid + '_timer'
  console.log(`ws客户端已经连接，当前是第${Object.keys(clients).length + 1}个连接的ws客户端 wsid为${wsid}`);
  if (Object.keys(clients).length > 0) {
    console.log("最多只有一个可以连接，新的ws连接失败")
    ws.close()
  }
  else {
    clients[wsid] = ws

    //收到消息
    ws.on('message', (message) => {
      console.log(`Received: ${message}`);
      wss.clients.forEach((client) => {
        if (client !== ws && client.readyState === WebSocket.OPEN) {
          client.send(message);
        }
      });
    });

    // 定时向客户端发送消息
    clients[wsid_timer] = setInterval(() => {
      const message = getnowdate() + ' 来自ws服务端的问候 =' + Math.random();
      console.log("服务器消息 " + message)
      ws.send(`{"ttt":"${message}" }`);
    }, 1000); // 每隔5秒发送一次消息

    ws.on('close', () => {
      console.log('Client disconnected 删除 wsid--' + wsid);
      clearInterval(clients[wsid_timer])

      delete clients[wsid];
      delete clients[wsid + '_timer'];



    });
  }
});
//定时任务 每5秒执行
schedule.scheduleJob('*/5 * * * * *', async () => {
  xm_fb()   //定时发布的项目发布更新 
  xm_ybjz() //项目应标截止更新项目状态
  xm_xbjz() //项目询价截止更新项目状态
  xm_tbkz() //项目投标截止更新项目状态
  xm_tbjz()
  xm_kb() 
  xm_pbjz() //项目评标结束更新项目状态
  // update_gysjb()
  update_gysjb_pm() //项目为竞价结束的时候，更新竞价排名
})

//定时任务 每5秒执行
schedule.scheduleJob('*/2 * * * * *', async () => {
  // xm_fb()
  // xm_ybjz()
  // xm_tbjz()
  // xm_kb()
  // update_gysbqxj() //项目为标前询价中的时候，更新竞价状态和排名
  update_gysjb() //项目为竞价中的时候，更新竞价状态和排名
})


//测试接口服务
server.listen(7878, async function () {
  var host = 'localhost'
  var port = server.address().port
  console.log("应用实例，访问地址为 http://%s:%s", host, port);
})

